package com.line.tools.util;

import org.apache.commons.codec.binary.Base64;
import org.apache.commons.lang3.ArrayUtils;

import javax.crypto.Cipher;
import java.security.*;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.HashMap;
import java.util.Map;

public class RSAUtils {
	// 非对称密钥算法
	public static final String KEY_ALGORITHM = "RSA";
	/**
	 * 密钥长度，DH算法的默认密钥长度是1024 密钥长度必须是64的倍数，在512到65536位之间
	 */
	private static final int KEY_SIZE = 1024;

	public static void main(String[] args) throws Exception {
	}

	public static void getKey() throws Exception {
		Map<String, Object> map = initKey();
		System.err.println("公钥：\n" + getPublicKey(map));
		System.err.println("私钥：\n" + getPrivateKey(map));
	}

	/**
	 * 初始化密钥对
	 * 
	 * @return Map 甲方密钥的Map
	 */
	public static Map<String, Object> initKey() throws Exception {
		// 实例化密钥生成器
		KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance(KEY_ALGORITHM);
		// 初始化密钥生成器
		keyPairGenerator.initialize(KEY_SIZE);
		// 生成密钥对
		KeyPair keyPair = keyPairGenerator.generateKeyPair();
		// 甲方公钥
		RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();
		// 甲方私钥
		RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();
		// 将密钥存储在map中
		Map<String, Object> keyMap = new HashMap<String, Object>();
		keyMap.put("publicKey", publicKey);
		keyMap.put("privateKey", privateKey);
		return keyMap;

	}

	/**
	 * 获取公钥字符串
	 * 
	 * @return 公钥字符串
	 * @throws Exception
	 *             异常
	 */
	public static String getPublicKey(Map<String, Object> map) throws Exception {
		Key key = (Key) map.get("publicKey");
		return Base64.encodeBase64String(key.getEncoded());
	}

	/**
	 * 获取私钥串
	 * 
	 * @return 私钥字符串
	 * @throws Exception
	 *             异常信息
	 */
	public static String getPrivateKey(Map<String, Object> map) throws Exception {
		Key key = (Key) map.get("privateKey");
		return Base64.encodeBase64String(key.getEncoded());
	}

	/**
	 * 私钥加密
	 * 
	 * @param originalText
	 *            需要加密的原文
	 * @param privateKey
	 *            私钥
	 * @return 加密后的字符串
	 */
	public static String encryptPrivate(String originalText, String privateKey) throws Exception {
		// BASE64解密
		byte[] decodeKey = Base64.decodeBase64(privateKey);
		byte[] decodeOriginal = originalText.getBytes();
		// 取得私钥
		PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(decodeKey);
		KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
		// 生成私钥
		PrivateKey priKey = keyFactory.generatePrivate(pkcs8KeySpec);
		// 数据加密
		Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
		cipher.init(Cipher.ENCRYPT_MODE, priKey);
		StringBuilder sb = new StringBuilder();
		byte[] dataReturn = null;
		for (int i = 0; i < decodeOriginal.length; i += 100) {
			byte[] doFinal = cipher.doFinal(ArrayUtils.subarray(decodeOriginal, i, i + 100));
			sb.append(new String(doFinal));
			dataReturn = ArrayUtils.addAll(dataReturn, doFinal);
		}
		return Base64.encodeBase64String(dataReturn);
	}

	/**
	 * 公钥加密
	 * 
	 * @param originalText
	 *            需要加密的原文
	 * @param publicKey
	 *            公钥
	 * @return 加密后的字符串
	 */
	public static String encryptPublic(String originalText, String publicKey) throws Exception {
		// BASE64解密
		byte[] decodeKey = Base64.decodeBase64(publicKey);
		byte[] decodeOriginal = originalText.getBytes();
		// 实例化密钥工厂
		KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
		// 初始化公钥
		// 密钥材料转换
		X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(decodeKey);
		// 产生公钥
		PublicKey pubKey = keyFactory.generatePublic(x509KeySpec);

		// 数据加密
		Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
		cipher.init(Cipher.ENCRYPT_MODE, pubKey);
		StringBuilder sb = new StringBuilder();
		byte[] dataReturn = null;
		for (int i = 0; i < decodeOriginal.length; i += 100) {
			byte[] doFinal = cipher.doFinal(ArrayUtils.subarray(decodeOriginal, i, i + 100));
			sb.append(new String(doFinal));
			dataReturn = ArrayUtils.addAll(dataReturn, doFinal);
		}
		return Base64.encodeBase64String(dataReturn);
	}

	/**
	 * 私钥解密
	 * 
	 * @param cipherText
	 *            密文
	 * @param privateKey
	 *            私钥
	 * @return 解密后的字符串
	 * @throws Exception
	 *             异常信息
	 */
	public static String decryptPrivate(String cipherText, String privateKey) throws Exception {
		// BASE64解密
		byte[] decodeKey = Base64.decodeBase64(privateKey);
		byte[] decodeCipher = Base64.decodeBase64(cipherText);
		// 取得私钥
		PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(decodeKey);
		KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
		// 生成私钥
		PrivateKey priKey = keyFactory.generatePrivate(pkcs8KeySpec);
		// 数据解密
		Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
		cipher.init(Cipher.DECRYPT_MODE, priKey);

		StringBuilder sb = new StringBuilder();
		for (int i = 0; i < decodeCipher.length; i += 128) {
			byte[] doFinal = cipher.doFinal(ArrayUtils.subarray(decodeCipher, i, i + 128));
			sb.append(new String(doFinal));
		}
		String dataReturn = sb.toString();
		return new String(dataReturn);
	}

	/**
	 * 公钥解密
	 * 
	 * @param cipherText
	 *            密文
	 * @param publicKey
	 *            公钥
	 * @return 解密后的字符串
	 * @throws Exception
	 *             异常信息
	 */
	public static String decryptPublic(String cipherText, String publicKey) throws Exception {
		// BASE64解密
		byte[] decodeKey = Base64.decodeBase64(publicKey);
		byte[] decodeCipher = Base64.decodeBase64(cipherText);
		// 实例化密钥工厂
		KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
		// 初始化公钥
		// 密钥材料转换
		X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(decodeKey);
		// 产生公钥
		PublicKey pubKey = keyFactory.generatePublic(x509KeySpec);
		// 数据解密
		Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
		cipher.init(Cipher.DECRYPT_MODE, pubKey);
		StringBuilder sb = new StringBuilder();
		for (int i = 0; i < decodeCipher.length; i += 128) {
			byte[] doFinal = cipher.doFinal(ArrayUtils.subarray(decodeCipher, i, i + 128));
			sb.append(new String(doFinal));
		}
		String dataReturn = sb.toString();
		return new String(dataReturn);
	}
}
